<?php

namespace app\weixin\controller;

//玩家答题日志
class UserAnswer extends Base{

    public function _initialize(){
        parent::_initialize();
    }

    public function index(){
        $map = [];
        $start = input("start");
        $end = input("end");
        if(!empty($start) && empty($end)){
            $map["s.create_time"] = array("egt",strtotime($start));
        }else if(!empty($end) && empty($start) ){
            $map["s.create_time"] = array("elt",strtotime($end));
        }else if(!empty($start) && !empty($end)){
            $map["s.create_time"][] = array("egt",strtotime($start));
            $map["s.create_time"][] = array("elt",strtotime($end));
        }
        $pagesize = config('paginate')['list_rows'];//每页数量
        // if(input('answer')=='export')$pagesize=10000000;
        $param=request()->param(); //获取url参数
        $lists = db('user')
            ->alias('u')
            ->join('user_subject_pk s', 'u.id = s.user_id')
            ->field('u.id,u.display_name,u.avatar,u.grad_name,u.count_changshu,u.count_wins,u.points,u.exp,u.curr_grad_start,count(s.id) as count')
            ->where($map)
            ->group('u.id')
            ->paginate($pagesize,false,array('query' => array_splice($param,1)));;
        if(input('answer')=='export'){
            $this->export_answer_list($lists);
        }
        $this->assign("lists",$lists);
        $this->assign("page", $lists->render());
        return $this->fetch();
    }

    //导出玩家答题日志
    public function export_answer_list($lists) { 
        set_time_limit(0);
        ignore_user_abort(true); 
        
        if (empty($lists)) {
            return json("数据为空！", 500);
        }
        $export_data = array();
        foreach ($lists as $key => $val) {
            $data["id"] = $val["id"];
            $data["avatar"] = $val["avatar"];
            $data["display_name"] = $val["display_name"];
            $data["grad_name"] = $val["grad_name"];
            $data["count_wins"] = $val["count_wins"];
            $data["count_fails"] = $val["count_changshu"]-$val["count_wins"];
            $data["points"] = $val["points"];
            $data["exp"] = $val["exp"];
            $data["curr_grad_start"] = $val["curr_grad_start"];
            $data["count"] = $val["count"];
            $export_data[$key] = $data;
        }
        \think\Loader::import('org.Excel', EXTEND_PATH);//导入第三方类库文件
        $file = \Excel::export_excel("UserAnswerList.xlsx", "", $export_data, 2);
        header('Location:'.DOWNLOAD_URL.$file);
    }
} 